package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmploeyyServiceImpl implements EmployeeService {
    @Autowired(required = false)
    private EmployeeMapper employeeMapper;
    @Override
    public R<Employee> login(Employee employee) {
        Employee loginEmployee = employeeMapper.login(employee);
        if (loginEmployee==null){
            throw new BusinessException("用户名或密码错误");
        }
        String s = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if (!s.equals(loginEmployee.getPassword())){
            throw new BusinessException("用户名或密码错误");
        }
        if (loginEmployee.getStatus()==0){
            throw new BusinessException("账号被禁用,请联系管理员");
        }
        return  R.success(loginEmployee);
    }

    @Override
    public void add(Employee employee) {
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);
        employeeMapper.save(employee);
    }

    @Override
    public Page<Employee> findByPage(Integer page, Integer pageSize, String name) {
        //设置分页查询第几页和每页多少条
        PageHelper.startPage(page,pageSize);
        //执行查询所有的sql语句方法
        List<Employee> employeeList = employeeMapper.findByName(name);
        //使用pageInfo封装上面的结果
        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);

        Page<Employee> pageObj = new Page<>();
        pageObj.setRecords(pageInfo.getList());
        pageObj.setTotal(pageInfo.getTotal());
        return pageObj;
    }

    @Override
    public Boolean update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        return employeeMapper.update(employee)>0;
    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }
}
